package com.xuzhiguang.lightnat.common.manager;

import com.xuzhiguang.lightnat.common.constant.AttributeKeyConstant;
import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;

public class ControlChannelManager {

    private static final ConcurrentHashMap<Long, Channel> channelMap = new ConcurrentHashMap<>();

    public static Channel add(long clientId, Channel channel) {
        Channel oldChannel = channelMap.put(clientId, channel);
        channel.attr(AttributeKeyConstant.clientIdKey).set(clientId);
        return oldChannel;
    }

    public static void remove(Channel channel) {
        Long clientId = getClientId(channel);
        if (clientId != null) {
            channelMap.remove(clientId);
        }
    }

    public static Long getClientId(Channel channel) {
        return channel.attr(AttributeKeyConstant.clientIdKey).get();
    }

    public static Channel getChannel(long clientId) {
        return channelMap.get(clientId);
    }

    public static void setAuthed(Channel channel, boolean authed) {
        channel.attr(AttributeKeyConstant.authedKey).set(authed);
    }

    public static Boolean getAuthed(Channel channel) {
        return channel.attr(AttributeKeyConstant.authedKey).get();
    }

}
